package com.controller;

import com.pojo.Menu;
import com.pojo.User;
import com.service.MenuService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class WebController {

	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;

	@PostMapping("/login")
	public String login(User user, Model model, HttpSession session) {
		User existingUser = userService.findUserByUsername(user.getUsername());
		if (existingUser != null && existingUser.getPassword().equals(user.getPassword()) && existingUser.getRole().equals(user.getRole())) {
			session.setAttribute("user", existingUser);
			return "redirect:/index";
		} else {
			model.addAttribute("tips", "用户名或密码错误，请重试！");
			return "login";
		}
	}

	@PostMapping("/register")
	public String register(User user, String password2, Model model) {
		if (!user.getPassword().equals(password2)) {
			model.addAttribute("tips", "两次密码输入不一致，请重试！");
			return "register";
		}
		if (userService.findUserByUsername(user.getUsername()) != null) {
			model.addAttribute("tips", "用户名已存在，请更换用户名！");
			return "register";
		}
		userService.registerUser(user);
		model.addAttribute("tips", "注册成功，请登录！");
		return "login";
	}

	@PostMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "login";
	}

	@GetMapping("/index")
	public String toIndex(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (user == null){
			return "login";
		}
		List<Menu> menus = menuService.findMenusByRoleFlag(user.getRole());
		model.addAttribute("menus", menus);
		return "index";
	}

}
